package org.ezplatform.office.forum.web.rest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.forum.entity.ForumType;
import org.ezplatform.office.forum.service.ForumTypeService;
import org.ezplatform.util.UuidUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 论坛类别控制类
 * 2019年11月2日17:40:59
 * @author Administrator
 *
 */
@RestController
@RequestMapping(value = "/api/w/forum/type")
public class ForumTypeWebApiController extends BaseController<ForumType, String> {
	
    private final Logger LOGGER = LoggerFactory.getLogger(ForumTypeWebApiController.class);

    @Autowired
    private ForumTypeService forumTypeService;
    
    @Autowired
	private LogService logService;

    @Override
    protected BaseService<ForumType, String> getEntityService() {
        return forumTypeService;
    }
    
    /**
     * 初始化数据
     * @param request
     * @param model
     * @param id
     */
    @ModelAttribute
    public void prepareModel(HttpServletRequest request, Model model,
                             @RequestParam(value = "id", required = false) String id) {
        super.initPrepareModel(request, model, id);
    }
    
    /**
     * 获取列表（翻页）数据
     *
     * @param request
     * @return json
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions({"stdForum:forumCate:03"})
    public Page<Map> findByPage(HttpServletRequest request) {
        String corpId = WebUtils.getCurrentUser().getCorpId();
        Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
        List<PropertyFilter> filter = PropertyFilter.buildFiltersFromHttpRequest(ForumType.class, request);
        Page<Map> page = forumTypeService.findPage(pageable, filter, corpId, TOKEN);
        return page;
    }
    
    /**
     * 根据id获取信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions(value = {"stdForum:forumCate:03", "stdForum:forumCate:02"}, logical = Logical.OR)
    public OperationResult editShow(@RequestParam("id") String id,HttpServletRequest request) {
    	String logStatus = request.getParameter("logStatus");
    	ForumType type = forumTypeService.findOne(id);
    	if(!StringUtils.equals(logStatus, "1")) {
    		logService.saveModuleLog("forum:type:03", type.getName(), ""); 
        }
    	return OperationResult.buildSuccessResult(type);
    }
    
    /**
     * 保存/修改
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions(value = {"stdForum:forumCate:01", "stdForum:forumCate:02"}, logical = Logical.OR)
    public OperationResult editSave(@ModelAttribute("entity") ForumType entity, HttpServletRequest request, Model model) {
        boolean flag = forumTypeService.checkCodeUnique(entity);
        OperationResult result ;
        if(flag) {
        	if(entity.getId()==null||StringUtils.isBlank(entity.getId())) {
        		logService.saveModuleLog("forum:type:01", entity.getName(), ""); 
        	}else {
        		ForumType type = forumTypeService.findOne(entity.getId());
        		logService.saveModuleLog("forum:type:02", type.getName(), ""); 
        	}
            result = this.editSave(entity);
        } else {
        	Map resources = new HashMap();
    		//国际化资源
            resources.put("i18NCode", "oa.forum.tips1");
            result = OperationResult.buildFailureResult("您输入的类别编码已存在",resources);
            //result = new OperationResult(OperationResult.OPERATION_RESULT_TYPE.failure, "您输入的类别编码已存在");
        }
        return result;
    }
    
    /**
     * 查询类别下是否有版块
     * @param request
     * @return
     */
    @RequestMapping(value = "/ifDelete", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions({"stdForum:forumCate:04"})
    public OperationResult ifDelete(HttpServletRequest request) {
    	String id = request.getParameter("id");
    	Map<String,String> data = new HashMap();
    	//查询类别下是否有版块
    	if(forumTypeService.ifDelete(id)) {
    		data.put("ifPost", "true");
    	}else {
    		data.put("ifPost", "false");
    	}
    	return OperationResult.buildSuccessResult(data);
    }
    
    /**
     * 删除（批量）数据
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions({"stdForum:forumCate:04"})
    public OperationResult delete(@RequestParam("ids") String... ids) {
    	OperationResult result ;
    	if(forumTypeService.checkDelete(ids)) {
    		result = forumTypeService.logicDelete(ids);
    	}
    	else {
    		List<String> idlist = Arrays.asList(ids);
    		for (String id : idlist) {
    			if(StringUtils.isNotBlank(id)) {
    				ForumType f = forumTypeService.findOne(id);
        			logService.saveModuleLog("forum:type:04", f.getName(), "",UuidUtils.UUID());
    			}
			}
    		Map resources = new HashMap();
    		//国际化资源
            resources.put("i18NCode", "oa.forum.deltips");
            result = OperationResult.buildFailureResult("所选类别下存在版块无法删除",resources);
    		//result = new OperationResult(OperationResult.OPERATION_RESULT_TYPE.failure, "所选类别下存在版块无法删除");
    	}
    	return result;
    }
    
    /**
     * 获取列表（翻页）数据
     *
     * @param request
     * @return json
     */
    @RequestMapping(value = "/getAllType", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult findAllLabel(HttpServletRequest request) {
        List list = forumTypeService.findAllLabel(WebUtils.getCurrentUser().getCorpId());
        return OperationResult.buildSuccessResult(list);
    }
}